package com.bbs.service.impl;

import com.bbs.dao.NiceDao;
import com.bbs.entity.Nice;
import com.bbs.entity.Post;
import com.bbs.service.NiceService;
import com.bbs.service.PostService;
import com.bbs.service.UserService;
import com.bbs.utils.MyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component("niceService")
public class NiceServiceImpl implements NiceService {
    @Autowired
    private NiceDao niceDao;
    @Autowired
    private PostService postService;
    @Autowired
    private UserService userService;
    @Override
    public int updateNice(int pid, Integer uid) {
        Post post = postService.findById(pid);
        Nice nice = niceDao.findByPidAndUid(pid, uid);
        if (nice == null) {
            niceDao.updateNice(pid, 1);
            nice = new Nice();
            nice.setPid(pid);
            nice.setUid(uid);
            nice.setNiceTime(MyUtil.formatDate(new Date()));
            niceDao.save(nice);
            post.setLikeCount(post.getLikeCount() + 1);
            userService.updateUserLikeCount(post.getUid());
            return post.getLikeCount();
        } else {
            niceDao.updateNice(pid, -1);
            niceDao.deleteByPidAndUid(pid, uid);
            post.setLikeCount(post.getLikeCount() - 1);
            userService.updateUserLikeCount2(post.getUid());
        }

        return post.getLikeCount();
    }
}
